package com.star.ms.admin.shiro;

import com.star.ms.admin.service.user.PermService;
import com.star.ms.admin.service.user.RoleService;
import com.star.ms.admin.service.user.UserService;
import com.star.ms.common.pojo.user.Perm;
import com.star.ms.common.pojo.user.Role;
import com.star.ms.common.pojo.user.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.List;


public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermService permService;
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String principal = (String) principalCollection.getPrimaryPrincipal();
        // 获取当前的用户信息
        User user = userService.getByCode(principal);
        if(user != null){
            // 获取用户的角色
            Role role = roleService.getByUserCode(user.getUsercode());
            user.setRole(role);
            // 赋予当前用户对应的角色信息（相同角色的权限是一致的）
            if(role != null) {
                info.addRole(role.getName());
//                 添加权限
                List<Perm> perms = permService.getByRoleId(role.getId());
                if(perms!=null && !CollectionUtils.isEmpty(perms)) {
                    perms.forEach(perm -> {
                        info.addStringPermission(perm.getUrl());
                    });
                }
            }
        }
        return info;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        // 获取身份信息
        String principal = (String) token.getPrincipal();
        // 调用业务层，获取数据库里对应的用户信息
        User user = userService.getByCode(principal);
        if(!ObjectUtils.isEmpty(user)){
            return new SimpleAuthenticationInfo(
                    principal,
                    user.getPassword(),
                    ByteSource.Util.bytes(user.getSalt()),
                    this.getName());
        }
        else return null;
    }
}
